package com.example.weixinapireptile.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.weixinapireptile.api.RedisCache;
import com.example.weixinapireptile.api.WeiXinApi;
import com.example.weixinapireptile.common.exceptions.BizException;
import com.example.weixinapireptile.common.utils.ThreadUtil;
import com.example.weixinapireptile.dingding.DingDingBot;
import com.example.weixinapireptile.model.Article;
import com.example.weixinapireptile.model.BizData;
import com.example.weixinapireptile.model.WxResultBody;
import com.example.weixinapireptile.pojo.entity.WxArticle;
import com.example.weixinapireptile.pojo.entity.WxArticleClassify;
import com.example.weixinapireptile.reptile.SpiderUtil;
import com.example.weixinapireptile.service.IWxArticleClassifyService;
import com.example.weixinapireptile.service.IWxArticleService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @version: java version 1.8
 * @Author: ljc  定时爬取处理
 * @description:
 * @date: 2024-03-06 9:45
 */
@Service
@Slf4j
public class WeixinDataPqHandler {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IWxArticleClassifyService iWxArticleClassifyService;

    @Autowired
    private IWxArticleService iWxArticleService;


    public void paiquHistory() throws ApiException {
        log.info("爬取全部历史数据开始=======");
        // ok
        List<WxArticleClassify> classifyList = iWxArticleClassifyService.list();
        if (CollUtil.isNotEmpty(classifyList)) {
            for (WxArticleClassify classify : classifyList) {
                log.info("爬取全部历史数据开始,当前公众号:{}", classify.getClassifyName());
                //获取公众号fack_id
                WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz(classify.getClassifyName());

                List<BizData> list = searchBiz.getList();
                if (list.isEmpty()) {
                    throw new BizException("公众号:" + classify.getClassifyName() + "不存在");
                }
                //查找公众号文章列表______爬取
                //第一次爬取获取数量分页信息
                WxResultBody<List<Article>> findExList;
                try {
                    findExList = WeiXinApi.findExList2(list.get(0).getFakeid(), "0", "5");
                } catch (Exception e) {
                    log.error("爬取全部历史数据失效频繁!!,当前公众号:{},当前页数:{}", classify.getClassifyName(), 0);
                    //todo 清除 cookie  token
                    redisCache.deleteObject("cookie");
                    redisCache.deleteObject("token");
//                    redisCache.setCacheObject(classify.getId(), String.valueOf(0));
                    //todo 钉钉 提醒
                    DingDingBot.sendBot();
                    throw new RuntimeException("接口频繁!!请重新扫码登录!");
                }

                //文章列表总数
                Integer appMsgCnt = findExList.getApp_msg_cnt();
                int pageNum = Math.round((float) appMsgCnt / 17);
                //从redis获取页数
                int start = 0;
                String begin = redisCache.getCacheObject(classify.getId());
                if (begin != null) {
                    start = Integer.parseInt(begin);
                }
                //循环爬取
                for (int i = start; i < pageNum; i++) {
                    redisCache.setCacheObject(classify.getId(), String.valueOf(i));
                    WxResultBody<List<Article>> findExLists;
                    try {
                        findExLists = WeiXinApi.findExList2(list.get(0).getFakeid(), String.valueOf(i), "17");
                        log.error("爬取全部历史数据ing!!,当前公众号:{},当前页数:{}", classify.getClassifyName(), i);

                    } catch (Exception e) {
                        log.error("爬取全部历史数据失效频繁!!,当前公众号:{},当前页数:{}", classify.getClassifyName(), i);
                        //todo 清除 cookie  token
                        // 1. POST请求开始登录接口，初始化cookie
                        redisCache.deleteObject("cookie");
                        redisCache.deleteObject("token");
                        redisCache.setCacheObject(classify.getId(), String.valueOf(i));
                        //todo 钉钉 提醒
                        DingDingBot.sendBot();
                        throw new RuntimeException("接口频繁!!请重新扫码登录!");
                    }


                    //保存
                    List<Article> exList = findExLists.getApp_msg_list();
                    int sum = 1;
                    for (Article article : exList) {
                        try {
                            WxArticle selectOne = iWxArticleService.getOne(new LambdaQueryWrapper<WxArticle>()
                                    .eq(WxArticle::getTitle, article.getTitle()).eq(WxArticle::getLink, article.getLink()));
                            if (ObjectUtil.isEmpty(selectOne)) {
                                LocalDate localDateTime = LocalDateTime.ofEpochSecond(article.getCreate_time(), 0, ZoneOffset.ofHours(8)).toLocalDate();
                                String content = SpiderUtil.getContent(article.getLink()).get("text");
                                String html = SpiderUtil.getContent(article.getLink()).get("html");
                                // 持久化入库
                                WxArticle wxArticle = new WxArticle();
                                wxArticle.setId(article.getAid());
                                wxArticle.setTitle(article.getTitle());
                                wxArticle.setLink(article.getLink());
                                wxArticle.setCoverImage(article.getCover());
                                wxArticle.setHtmlContent(html);
                                wxArticle.setClassifyId(classify.getId());
                                wxArticle.setPublishDate(localDateTime.toString());
                                wxArticle.setContent(content);
                                iWxArticleService.save(wxArticle);
                                sum++;
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }

                    }
                    log.info("保存:{}文章成功,数量:{}",classify.getClassifyName(), sum);
                    // 线程阻塞，防止访问频繁导致封号
                    ThreadUtil.wait(60);
                }
            }
            // 线程阻塞，防止访问频繁导致封号
//            ThreadUtil.wait(5);
        }
    }

    public void paiquHistoryOne(String id) throws ApiException {

        log.info("爬取单个历史数据开始=======");
        // ok
        WxArticleClassify classify = iWxArticleClassifyService.getById(id);
        log.info("当前单个公众号信息:{}", JSON.toJSONString(classify));
        if (null != classify) {

            log.info("爬取单个历史数据开始,当前公众号:{}", classify.getClassifyName());
            //获取公众号fack_id
            WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz(classify.getClassifyName());

            List<BizData> list = searchBiz.getList();
            if (list.isEmpty()) {
                throw new BizException("公众号:" + classify.getClassifyName() + "不存在");
            }
            //查找公众号文章列表______爬取
            //第一次爬取获取数量分页信息
            WxResultBody<List<Article>> findExList;
            try {
                findExList = WeiXinApi.findExList2(list.get(0).getFakeid(), "0", "5");
            } catch (Exception e) {
                log.error("爬取单个历史数据失效频繁!!,当前公众号:{},当前页数:{}", classify.getClassifyName(), 0);
                //todo 清除 cookie  token
                redisCache.deleteObject("cookie");
                redisCache.deleteObject("token");
                redisCache.setCacheObject(classify.getId(), String.valueOf(0));
                //todo 钉钉 提醒
                DingDingBot.sendBot();
                throw new RuntimeException("接口频繁!!请重新扫码登录!");
            }

            //文章列表总数
            Integer appMsgCnt = findExList.getApp_msg_cnt();
            int pageNum = Math.round((float) appMsgCnt / 17);
            //从redis获取页数
            int start = 0;
            String begin = redisCache.getCacheObject(classify.getId());
            if (begin != null) {
                start = Integer.parseInt(begin);
            }
            //循环爬取
            for (int i = start; i < pageNum; i++) {
                redisCache.setCacheObject(classify.getId(), String.valueOf(i));
                WxResultBody<List<Article>> findExLists;
                try {
                    findExLists = WeiXinApi.findExList2(list.get(0).getFakeid(), String.valueOf(i), "17");
                    log.error("爬取单个历史数据ing!!,当前公众号:{},当前页数:{},包含文章数:{}", classify.getClassifyName(), i,findExLists.getApp_msg_list().size());


                } catch (Exception e) {
                    log.error("爬取单个历史数据失效频繁!!,当前公众号:{},当前页数:{}", classify.getClassifyName(), i);
                    //todo 清除 cookie  token
                    // 1. POST请求开始登录接口，初始化cookie
                    redisCache.deleteObject("cookie");
                    redisCache.deleteObject("token");
                    redisCache.setCacheObject(classify.getId(), String.valueOf(i));
                    //todo 钉钉 提醒
                    DingDingBot.sendBot();
                    throw new RuntimeException("接口频繁!!请重新扫码登录!");
                }


                //保存
                List<Article> exList = findExLists.getApp_msg_list();
                int sum = 0;
                for (Article article : exList) {
                    WxArticle selectOne = iWxArticleService.getOne(new LambdaQueryWrapper<WxArticle>()
                            .eq(WxArticle::getId,article.getAid()).eq(WxArticle::getTitle, article.getTitle()).eq(WxArticle::getLink, article.getLink()));
                    if (ObjectUtil.isEmpty(selectOne)) {
                        LocalDate localDateTime = LocalDateTime.ofEpochSecond(article.getCreate_time(), 0, ZoneOffset.ofHours(8)).toLocalDate();
                        String content = SpiderUtil.getContent(article.getLink()).get("text");
                        String html = SpiderUtil.getContent(article.getLink()).get("html");
                        // 持久化入库
                        WxArticle wxArticle = new WxArticle();
                        wxArticle.setId(article.getAid());
                        wxArticle.setTitle(article.getTitle());
                        wxArticle.setLink(article.getLink());
                        wxArticle.setCoverImage(article.getCover());
                        wxArticle.setHtmlContent(html);
                        wxArticle.setClassifyId(classify.getId());
                        wxArticle.setPublishDate(localDateTime.toString());
                        wxArticle.setContent(content);
                        iWxArticleService.save(wxArticle);
                        sum++;
                    }
                }
                log.info("保存文章成功,数量:{}", sum);
                // 线程阻塞，防止访问频繁导致封号
                ThreadUtil.wait(30);
            }

            // 线程阻塞，防止访问频繁导致封号
            //ThreadUtil.wait(5);
        }
    }
}

